Sphere intersection
We wish to find out when a ray hits a sphere. Our spheres will be defined by the implicit equation of a sphere $$ (\mathbf{p - c}) \cdot (\mathbf{p - c}) - r^2 = 0 $$
where \( \mathbf{p}) \) is the a possible position on the sphere, \( \mathbf{c}) \) is the center of the sphere, and \( r \) is the radius.
Given the parametric equation of a ray $$ \mathbf{r} = \mathbf{e} + t\mathbf{d}\ $$ we can solve for the intersection by setting the equations equal to one another. Put the ray equation in place of the \( \mathbf{p}\) in the sphere equation results in:
$$ (\mathbf{e} + t\mathbf{d} - \mathbf{c}) \cdot (\mathbf{e} + t\mathbf{d} - \mathbf{c}) - r^2 = 0; $$
This expands to:
$$ ( \mathbf{d} \cdot \mathbf{d}) t^2 + 2 \mathbf{d} \cdot (\mathbf{e} - \mathbf{c}) t + (\mathbf{e} - \mathbf{c}) \cdot (\mathbf{e} - \mathbf{c}) - r^2 = 0 $$
This result is solvable using the quadratic formula: $$ x = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a} $$
where
$$ a = \mathbf{d} \cdot \mathbf{d}) $$
$$ b = 2 \mathbf{d} \cdot (\mathbf{e} - \mathbf{c}) $$
$$ c = (\mathbf{e} - \mathbf{c}) \cdot (\mathbf{e} - \mathbf{c}) - r^2 = 0 $$
We can then solve for t: $$ t = \frac{ - \mathbf{d} \cdot (\mathbf{e} - \mathbf{c}) \pm \sqrt{ ( \mathbf{d} \cdot (\mathbf{e} - \mathbf{c}))^2 - (\mathbf{d} \cdot \mathbf{d}) ( (\mathbf{e} - \mathbf{c}) \cdot (\mathbf{e} - \mathbf{c}) - r^2) }}{ (\mathbf{d} \cdot \mathbf{d}) } $$